
package session.stateless.FRM;

import entity.FRM.SupplierInvoice;
import entity.SCM.MaterialOrder;
import entity.SCM.Supplier;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class SupplierInvoiceBean implements SupplierInvoiceBeanLocal {
    @PersistenceContext 
    private EntityManager em;
    
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
    
    @Override
    public Long createSupplierInvoice(Long materialOrderId, Double finalAmount) {
         MaterialOrder materialOrder = em.find(MaterialOrder.class, materialOrderId);
         Supplier supplier = materialOrder.getSupplier();
         SupplierInvoice supplierInvoice = new SupplierInvoice();
         
         Date date = new Date();
         supplierInvoice.setSupplierInvoiceDate(dateFormat.format(date));
         supplierInvoice.setMaterialOrder(materialOrder);
         supplierInvoice.setStateSupplierInvoice(SupplierInvoice.StateSupplierInvoice.Pending);
         supplierInvoice.setSupplierInvoiceAmount(finalAmount);
         
         em.persist(supplierInvoice);
         
         supplier.getSupplierInvoices().add(supplierInvoice);
         em.flush();
         
         return supplierInvoice.getSupplierInvoiceId();
    }

    @Override
    public List<SupplierInvoice> getAllSupplierInvoices() {
        Query query = em.createQuery("SELECT c FROM SupplierInvoice c");
        return query.getResultList();
    }

    @Override
    public List<SupplierInvoice> getAllSupplierInvoices_Pending() {
        Query query = em.createQuery("SELECT c FROM SupplierInvoice c WHERE c.stateSupplierInvoice =:state");
        query.setParameter("state", SupplierInvoice.StateSupplierInvoice.Pending);
        return query.getResultList();
    }

    @Override
    public SupplierInvoice findSupplierInvoice(Long supplierInvoiceId) {
        SupplierInvoice temp = em.find(SupplierInvoice.class, supplierInvoiceId);
        return temp;
        
    }

}
